using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;
using System.Collections.Generic;
using Commonplace.Domain;
using Commonplace.Controller;
using System.Xml;

namespace Commonplace
{
	/// <summary>
	/// Summary description for OptionsDialog.
	/// </summary>
	public class OptionsDialog : System.Windows.Forms.Form
	{
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox _defaultLicense;
		private System.Windows.Forms.Button _forgetLogin;
		private System.Windows.Forms.CheckBox _addToWatch;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Label _loginStatus;
		private System.Windows.Forms.Button _ok;
        private System.Windows.Forms.Button _cancel;
        private System.ComponentModel.IContainer components;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.CheckBox _checkNewVersion;
		private System.Windows.Forms.Button _checkNewVersionNow;
        private Label _currentWiki;
        private Button _changeWiki;
        private OpenFileDialog _pickWikiConnection;
        private Button _toCommons;
		private System.Windows.Forms.CheckBox _useInfoTemplate;
        private ToolTip _toolTip;

        WikiConnectionConfig _wikiConfig = new WikiConnectionConfig();



		public OptionsDialog()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			LoadConfig();

		}

		private void LoadConfig()
		{
			StoredConfig config = new StoredConfig();

            List<License> licenses = new List<License>();
            List<string> licenseStrings = config.GetList("license");
            foreach (string licenseString in licenseStrings)
            {
                if (true == licenseString.Contains("|"))
                    licenses.Add(new License(licenseString));
            } 
            _defaultLicense.Items.AddRange(licenses.ToArray());


			string username = config["username"];
			string watchUploads = config["watchuploads"];
			string defaultLicense = config["defaultlicense"];
			string useInfoTemplate = config["useinfotemplate"];
			string checkNewVersion = config["autoupdate"];

            string wiki = config["wiki"];
            if (string.Empty != wiki)
                _wikiConfig = new WikiConnectionConfig(wiki);            

			if (username.Length > 0)
			{
				_loginStatus.Text = "Your login information is currently saved.";
				_forgetLogin.Enabled = true;
			}
			else
			{
				_loginStatus.Text = "Your login is not saved.";
				_forgetLogin.Enabled = false;
			}

			if ("true" == watchUploads)
				_addToWatch.Checked = true;
			else
				_addToWatch.Checked = false;

			if ("false" == useInfoTemplate)
				_useInfoTemplate.Checked = false;
			else
				_useInfoTemplate.Checked = true;

			if ("" == checkNewVersion || "true" == checkNewVersion)
				_checkNewVersion.Checked = true;
			else
				_checkNewVersion.Checked = false;

            _defaultLicense.Items.Clear();
            List<string> licenseData = config.GetList("licenses");
            _defaultLicense.Items.Add(License.None);
            foreach (string licenseString in licenseData)
            {
                _defaultLicense.Items.Add(new License(licenseString));
            }
			
			if (defaultLicense.Length > 0)
				_defaultLicense.Text = defaultLicense;
			else
				_defaultLicense.Text = License.None.Name;

            UpdateWikiInfo();

		}

		public void SaveConfig()
		{
			StoredConfig config = new StoredConfig();

            List<string> licenseData = new List<string>();
            foreach (License license in _defaultLicense.Items)
            {
                if (license.Data.Length > 0)
                    licenseData.Add(license.Data);
            }

            config.UpdateList("licenses", licenseData);

			if (true == _addToWatch.Checked)
				config["watchuploads"] = "true";
			else
				config["watchuploads"] = "false";
			
			if (_defaultLicense.Text.Trim().Length > 0 && "NONE" != _defaultLicense.Text.ToUpper())
				config["defaultlicense"] = _defaultLicense.Text;
			else
				config["defaultlicense"] = null;
			
			if (true == _useInfoTemplate.Checked)
				config["useinfotemplate"] = "true";
			else
				config["useinfotemplate"] = "false";
			
			if (true == _checkNewVersion.Checked)
				config["autoupdate"] = "true";
			else
				config["autoupdate"] = "false";

            config["wiki"] = _wikiConfig.ToString();

			config.Save();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this._forgetLogin = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this._useInfoTemplate = new System.Windows.Forms.CheckBox();
            this._addToWatch = new System.Windows.Forms.CheckBox();
            this._defaultLicense = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this._loginStatus = new System.Windows.Forms.Label();
            this._ok = new System.Windows.Forms.Button();
            this._cancel = new System.Windows.Forms.Button();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this._toCommons = new System.Windows.Forms.Button();
            this._changeWiki = new System.Windows.Forms.Button();
            this._currentWiki = new System.Windows.Forms.Label();
            this._checkNewVersionNow = new System.Windows.Forms.Button();
            this._checkNewVersion = new System.Windows.Forms.CheckBox();
            this._pickWikiConnection = new System.Windows.Forms.OpenFileDialog();
            this._toolTip = new System.Windows.Forms.ToolTip(this.components);
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.SuspendLayout();
            // 
            // _forgetLogin
            // 
            this._forgetLogin.Enabled = false;
            this._forgetLogin.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._forgetLogin.Location = new System.Drawing.Point(48, 56);
            this._forgetLogin.Name = "_forgetLogin";
            this._forgetLogin.Size = new System.Drawing.Size(96, 23);
            this._forgetLogin.TabIndex = 1;
            this._forgetLogin.Text = "&Forget my login";
            this._toolTip.SetToolTip(this._forgetLogin, "Will no longer remember your login, prompting you for your username and password " +
                    "next time you try to upload files.");
            this._forgetLogin.Click += new System.EventHandler(this._forgetLogin_Click);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this._useInfoTemplate);
            this.groupBox1.Controls.Add(this._addToWatch);
            this.groupBox1.Controls.Add(this._defaultLicense);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.groupBox1.Location = new System.Drawing.Point(16, 16);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(328, 96);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "File Options";
            // 
            // _useInfoTemplate
            // 
            this._useInfoTemplate.Checked = true;
            this._useInfoTemplate.CheckState = System.Windows.Forms.CheckState.Checked;
            this._useInfoTemplate.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._useInfoTemplate.Location = new System.Drawing.Point(8, 40);
            this._useInfoTemplate.Name = "_useInfoTemplate";
            this._useInfoTemplate.Size = new System.Drawing.Size(136, 24);
            this._useInfoTemplate.TabIndex = 1;
            this._useInfoTemplate.Text = "Use &information template";
            this._toolTip.SetToolTip(this._useInfoTemplate, "Will use the {{Information}} template for the file description.");
            // 
            // _addToWatch
            // 
            this._addToWatch.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._addToWatch.Location = new System.Drawing.Point(8, 16);
            this._addToWatch.Name = "_addToWatch";
            this._addToWatch.Size = new System.Drawing.Size(200, 24);
            this._addToWatch.TabIndex = 0;
            this._addToWatch.Text = "Add uploads to &watch list by default";
            this._toolTip.SetToolTip(this._addToWatch, "Uploaded files are automatically added to your watch list.");
            // 
            // _defaultLicense
            // 
            this._defaultLicense.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._defaultLicense.Items.AddRange(new object[] {
            "None",
            "{{cc-by-2.0}}",
            "{{cc-by-sa-2.0}}",
            "{{GFDL}}",
            "{{PD}}"});
            this._defaultLicense.Location = new System.Drawing.Point(96, 64);
            this._defaultLicense.Name = "_defaultLicense";
            this._defaultLicense.Size = new System.Drawing.Size(216, 21);
            this._defaultLicense.TabIndex = 3;
            this._toolTip.SetToolTip(this._defaultLicense, "The license that should be specified for the file being uploaded.");
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(5, 64);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(88, 21);
            this.label1.TabIndex = 2;
            this.label1.Text = "Default &license:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this._loginStatus);
            this.groupBox2.Controls.Add(this._forgetLogin);
            this.groupBox2.Location = new System.Drawing.Point(16, 120);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(328, 88);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Login Options";
            // 
            // _loginStatus
            // 
            this._loginStatus.Location = new System.Drawing.Point(8, 24);
            this._loginStatus.Name = "_loginStatus";
            this._loginStatus.Size = new System.Drawing.Size(304, 23);
            this._loginStatus.TabIndex = 0;
            this._loginStatus.Text = "Your login is not saved.";
            this._loginStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this._toolTip.SetToolTip(this._loginStatus, "The login you will use to authenticate with the wiki.");
            // 
            // _ok
            // 
            this._ok.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this._ok.DialogResult = System.Windows.Forms.DialogResult.OK;
            this._ok.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._ok.Location = new System.Drawing.Point(184, 333);
            this._ok.Name = "_ok";
            this._ok.Size = new System.Drawing.Size(75, 23);
            this._ok.TabIndex = 3;
            this._ok.Text = "&OK";
            // 
            // _cancel
            // 
            this._cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this._cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this._cancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._cancel.Location = new System.Drawing.Point(272, 333);
            this._cancel.Name = "_cancel";
            this._cancel.Size = new System.Drawing.Size(75, 23);
            this._cancel.TabIndex = 4;
            this._cancel.Text = "&Cancel";
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this._toCommons);
            this.groupBox3.Controls.Add(this._changeWiki);
            this.groupBox3.Controls.Add(this._currentWiki);
            this.groupBox3.Controls.Add(this._checkNewVersionNow);
            this.groupBox3.Controls.Add(this._checkNewVersion);
            this.groupBox3.Location = new System.Drawing.Point(16, 216);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(328, 107);
            this.groupBox3.TabIndex = 2;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Application Options";
            // 
            // _toCommons
            // 
            this._toCommons.Location = new System.Drawing.Point(221, 74);
            this._toCommons.Name = "_toCommons";
            this._toCommons.Size = new System.Drawing.Size(91, 23);
            this._toCommons.TabIndex = 3;
            this._toCommons.Text = "Use Commons";
            this._toolTip.SetToolTip(this._toCommons, "Switch back to using the Wikimedia Commons.");
            this._toCommons.UseVisualStyleBackColor = true;
            this._toCommons.Click += new System.EventHandler(this._toCommons_Click);
            // 
            // _changeWiki
            // 
            this._changeWiki.Location = new System.Drawing.Point(221, 45);
            this._changeWiki.Name = "_changeWiki";
            this._changeWiki.Size = new System.Drawing.Size(91, 23);
            this._changeWiki.TabIndex = 2;
            this._changeWiki.Text = "Change Wiki";
            this._toolTip.SetToolTip(this._changeWiki, "Open a WikiConnection file to upload to a different wiki.");
            this._changeWiki.UseVisualStyleBackColor = true;
            this._changeWiki.Click += new System.EventHandler(this._changeWiki_Click);
            // 
            // _currentWiki
            // 
            this._currentWiki.AutoSize = true;
            this._currentWiki.Location = new System.Drawing.Point(5, 50);
            this._currentWiki.Name = "_currentWiki";
            this._currentWiki.Size = new System.Drawing.Size(65, 13);
            this._currentWiki.TabIndex = 2;
            this._currentWiki.Text = "Current wiki:";
            this._toolTip.SetToolTip(this._currentWiki, "The wiki you where you will be uploading files.");
            // 
            // _checkNewVersionNow
            // 
            this._checkNewVersionNow.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._checkNewVersionNow.Location = new System.Drawing.Point(221, 16);
            this._checkNewVersionNow.Name = "_checkNewVersionNow";
            this._checkNewVersionNow.Size = new System.Drawing.Size(91, 23);
            this._checkNewVersionNow.TabIndex = 1;
            this._checkNewVersionNow.Text = "Check &now";
            this._toolTip.SetToolTip(this._checkNewVersionNow, "Force an immediate check for a new version of the application.");
            this._checkNewVersionNow.Click += new System.EventHandler(this._checkNewVersionNow_Click);
            // 
            // _checkNewVersion
            // 
            this._checkNewVersion.Checked = true;
            this._checkNewVersion.CheckState = System.Windows.Forms.CheckState.Checked;
            this._checkNewVersion.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this._checkNewVersion.Location = new System.Drawing.Point(8, 16);
            this._checkNewVersion.Name = "_checkNewVersion";
            this._checkNewVersion.Size = new System.Drawing.Size(207, 24);
            this._checkNewVersion.TabIndex = 0;
            this._checkNewVersion.Text = "Check for new &version on every startup";
            this._toolTip.SetToolTip(this._checkNewVersion, "The application will try to check for an updated version every time it starts up." +
                    "");
            // 
            // _pickWikiConnection
            // 
            this._pickWikiConnection.DefaultExt = "*.wikiconnection";
            this._pickWikiConnection.Filter = "WikiConnections|*.wikiconnection|All Files|*.*";
            // 
            // OptionsDialog
            // 
            this.AcceptButton = this._ok;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.CancelButton = this._cancel;
            this.ClientSize = new System.Drawing.Size(360, 365);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this._cancel);
            this.Controls.Add(this._ok);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "OptionsDialog";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Commonplace Options";
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.ResumeLayout(false);

		}
		#endregion

		private void _forgetLogin_Click(object sender, System.EventArgs e)
		{
			StoredConfig config = new StoredConfig();
			config["username"] = null;
			config["password"] = null;
			config.Save();

			LoadConfig();
		}

		private void _checkNewVersionNow_Click(object sender, System.EventArgs e)
		{
			AutoUpdate au = new AutoUpdate();
			au.GetNewFile();
		}

        private void _changeWiki_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == _pickWikiConnection.ShowDialog())
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(_pickWikiConnection.FileName);
                    _wikiConfig = new WikiConnectionConfig(doc.OuterXml);

                    UpdateWikiInfo();

                    ReloadLicenses();
                }
                catch
                {
                    MessageBox.Show("The file you selected was not a valid Wiki Connection.", "Wikimedia Commonplace", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void _toCommons_Click(object sender, EventArgs e)
        {
            _wikiConfig = new WikiConnectionConfig();

            UpdateWikiInfo();

            ReloadLicenses();
        }

        private void UpdateWikiInfo()
        {
            _currentWiki.Text = string.Format("Current wiki: {0}", _wikiConfig.Name);
            if (_wikiConfig.ToString() == (new WikiConnectionConfig().ToString()))
                _toCommons.Enabled = false;
            else
                _toCommons.Enabled = true;
        }

        private void ReloadLicenses()
        {
            List<License> licenses = LicenseLoader.LoadLicenses(_wikiConfig);

            _defaultLicense.Items.Clear();
            _defaultLicense.Items.Add(License.None);
            foreach (License license in licenses)
            {
                _defaultLicense.Items.Add(license);
            }

            _defaultLicense.SelectedIndex = 0;
        }
	}
}
